package com.obligatorio.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.obligatorio.ejb.ManejadorUsuario;

/**
 * Servlet implementation class ValidarCuenta
 */
@WebServlet(description = "Validar Registro de Usuairo", urlPatterns = { "/validar-cuenta" })
public class ValidarCuenta extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@EJB
	private ManejadorUsuario mUsuario;
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		
		response.setContentType("text/html;charset=UTF-8");
		String forwardTo = null;
		
		String code = request.getParameter("code");
		if(!code.isEmpty()){
			try {
				if(mUsuario.activarUsuario(code)){
					forwardTo = "/login.xhtml";//redirecciona a la pagina de login
				}else{
					//deberia redireccionar a una pagina de error
					String texto = "Incorrecta";
					this.test(response,texto);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		request.getRequestDispatcher(forwardTo).forward(request, response);
	}
	
	private void test(HttpServletResponse response,String text){		
        try {
        	PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Validacion de Cuenta</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Validacion "+text+".</h1>");
            out.println("</body>");
            out.println("</html>");
        }catch (Exception e) {
			System.out.println(e.toString());
		}
	}

}
